// pages/courseware/erji//coursewareInfo/coursewareInfo.js
var base = require('../../../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const PAGES = require('../../../../utils/pages.js')
const { HTTP } = require('../../../../lib/http.js')
const { URL } = require('../../../../lib/urls.js')
const { getUserToken, getUserInfo } = require('../../../../lib/user.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    VideoCourseInfos:null,
    dataList:[],
    nowPxType:0,
    paixuImg:"/resourse/courseware/paixu_desc.png",
    isFromSearch: true, // 用于判断searchSongList数组是不是空数组，默认true，空的数组
    searchPageNum: 1,   // 设置加载的第几次，默认是第一次
    callbackcount: 20,   //返回数据的个数
    searchLoading: false, //"上拉加载"的变量，默认false，隐藏
    searchLoadingComplete: false,  //“没有数据”的变量，默认false，隐藏
    isShowNullView: false,
    // 视频播放
    VideoUrl: '', //要播放的视频对象
    fullScreen: false, //视频是否全屏
    isShowVideo:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
    var item = JSON.parse(decodeURIComponent(options.data));
    if(item){
      this.setData({
        VideoCourseInfos:item,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.fetchDataList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      searchPageNum: 1,  //每次触发上拉事件，把searchPageNum+1
      isFromSearch: true  //触发到上拉事件，把isFromSearch设为为false
    });
    that.fetchDataList();
  },
  //滚动到底部触发事件
  onReachBottom: function () {
    let that = this;
    if (that.data.searchLoading && !that.data.searchLoadingComplete) {
      that.setData({
        searchPageNum: that.data.searchPageNum + 1,  //每次触发上拉事件，把searchPageNum+1
        isFromSearch: false  //触发到上拉事件，把isFromSearch设为为false
      });
      that.fetchDataList();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 点击项目
   */
  onItemTap: function (e) {
    var item = e.currentTarget.dataset.item;
    this.getNetVideoUrl(item);
  },
  /**
   * 购买或者播放
   */
  payOrPlay: function (e) {
    var item = e.currentTarget.dataset.item;
    if (item.CanPlay){
      //可以播放
      this.getNetVideoUrl(item);    
      return;
    }
    if(item.PriceType==3){
      //会员专享
      wx.navigateTo({
        url: PAGES.videoMember,
      })
    }else{
      //付费视屏
      this.getNetPayVideo(item.VideoCode);
    }
  },
  //排序点击
  onPaixuTap: function () {
    var pxType=this.data.nowPxType==0?1:0;
    var pxImg = pxType == 0 ? "/resourse/courseware/paixu_desc.png" : "/resourse/courseware/paixu_asc.png";
    this.setData({
      nowPxType:pxType,
      paixuImg:pxImg,
    });
    this.onPullDownRefresh();
  },
  //获取视频列表
  fetchDataList: function () {
    wx.showLoading({
      title: '加载中...'
    })
    let that = this;
    let searchPageNum = that.data.searchPageNum,//把第几次加载次数作为参数
      callbackcount = that.data.callbackcount; //返回数据的个数

    HTTP({
      url: URL.courseware.coursewareVideoList,
      userToken: getUserToken(),
      data: {
        Code: that.data.VideoCourseInfos ? that.data.VideoCourseInfos.VideoCourseCode : '',
        PageIndex: searchPageNum,
        PageSize: callbackcount,
        SortBy: that.data.nowPxType == 0 ? 'Sort ASC,ModifyDate desc ,createdate desc' :'Sort ASC,ModifyDate desc ,createdate asc',
      },
      success: (ress) => {
        wx.stopPullDownRefresh();
        wx.hideLoading();
        var res = ress.Data;
        if (res.VideoInfos.length > 0) {
          console.log("hlw:" + res)
          let searchList = [];
          var list = [];
          for (var i = 0; i < res.VideoInfos.length; i++) {
            var model = res.VideoInfos[i];
            if (model.PriceType==1){
              model.TypeName = _('免费试看');
            }else if(model.PriceType==2){
              model.TypeName = _('收费视频');
            }else{
              model.TypeName = _('会员专享');
            }
            if (model) {
              list.push(model);
            }
          }
          //如果isFromSearch是true从data中取出数据，否则先从原来的数据继续添加
          this.data.isFromSearch ? searchList = list : searchList = that.data.dataList.concat(list)
          this.setData({
            dataList: searchList, //获取数据数组
            searchLoading: true,   //把"上拉加载"的变量设为false，显示
            isShowNullView: searchList.length > 0 ? false : true
          });
          if (res.VideoInfos.length < callbackcount) {
            //数据已加载完毕
            that.setData({
              searchLoadingComplete: true, //把“没有数据”设为true，显示
              searchLoading: false  //把"上拉加载"的变量设为false，隐藏
            });
          }
          //没有数据了，把“没有数据”显示，把“上拉加载”隐藏
        } else {
          if (that.data.searchPageNum == 1) {
            that.setData({
              dataList: [],
              isShowNullView: true
            })
          }
          that.setData({
            searchLoadingComplete: true, //把“没有数据”设为true，显示
            searchLoading: false  //把"上拉加载"的变量设为false，隐藏
          });
        }
      }, fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //  购买视屏
  getNetPayVideo: function (code) {
    wx.showLoading({
      title: ''
    })
    let that = this;
    HTTP({
      url: URL.courseware.coursewareVideoPay,
      userToken: getUserToken(),
      data: {
        VideoCode: code,
      },
      success: (ress) => {
        wx.hideLoading();
        var res = ress.Data;
        //支付开始
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: function (res) {
            //支付成功
            wx.showToast({
              title: _('支付成功'),
              icon: 'succes',
              duration: 1000,
              mask: true
            })
            var list=[];
            for(var i=0;i<that.data.dataList.length;i++){
              var model=that.data.dataList[i];
              if(model.VideoCode==code){
                model.CanPlay=true;
              }
              list.push(model);
            }
            that.setData({
              dataList:list,
            });
          },
          fail: function (res) {
            console.log("hlwfail:" + res.data)
            wx.showToast({
              title: _('支付失败'),
              icon: 'none'
            })
          }
        })
        //支付结束
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  //  获取视频地址
  getNetVideoUrl: function (item) {
    wx.showLoading({
      title: ''
    })
    let that = this;
    HTTP({
      url: URL.courseware.coursewareVideoShow,
      userToken: getUserToken(),
      data: {
        Code: item.VideoCode,
      },
      success: (ress) => {
        wx.hideLoading();
        var res = ress.Message||'';
        if(res.length>0){
          if (item.VideoType==2){
            // 音频播放
            item.AudioUrl = res;
            var data = JSON.stringify(item);
            wx.navigateTo({
              url: PAGES.audioInfo + '?data=' + encodeURIComponent(data)
            })
          }else{
            // 视频播放
            that.setData({
              VideoUrl: res,
            });
            that.showVideo();
          }
        }else{
          wx.showToast({
            title: '无权限',
            icon: 'none'
          })
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  // 视频播放
  //弹出视频图层。播放视频
  showVideo:function() {
    
    wx.createVideoContext('myvideo').requestFullScreen({ direction: 90 });
    this.setData({
      fullScreen: true
    });
    
  },

  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法
    wx.createVideoContext('myvideo').exitFullScreen();
    this.setData({
      fullScreen: false
    });
  },
  /**视屏进入、退出全屏 */
  fullScreens(e) {
    var isFull = e.detail.fullScreen;
    //视屏全屏时显示加载video，非全屏时，不显示加载video
    this.setData({
      fullScreen: isFull
    })
  },
})